package com.bawei.mallshop.splash

import androidx.lifecycle.viewModelScope
import com.alibaba.android.arouter.launcher.ARouter
import com.bawei.common.mvi.BaseViewModel
import com.blankj.utilcode.util.SPUtils
import com.google.gson.Gson
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.launch

/**
 * @author ZhangRuiPeng
 * @description:
 */
class SplashViewModel : BaseViewModel<SplashRepository, SplashState>() {
    override fun createRepo(): SplashRepository {
        return SplashRepository()
    }

    override fun createSTATE(): SplashState {
        return SplashState(false, TokenEntity(""),false,"")
    }

    //构建请求token方法
    fun requestToken(){
        val map = HashMap<String,Any>()
        map.put("imie",System.currentTimeMillis())
        viewModelScope.launch {
            realContainer.updateRequestState {
                copy(true,false,false)
            }
            repo.requestToken(map)
                .flowOn(Dispatchers.IO)
                .catch {
                    realContainer.updateRequestState {
                        copy(false,false,true)
                    }
                }
                .collect{
                    if (it == null){
                        realContainer.updateRequestState {
                            copy(false,false,true)
                        }
                        return@collect
                    }
                    //由于token接口返回values中对应jsonobject中混入非法的转义字符
                    //gson无法一次完成映射,针对token接口手动解析一次
                    var tokenEntity : TokenEntity = Gson().fromJson(it.values,TokenEntity::class.java)
                    //通过sp存放token
                    SPUtils.getInstance().put("token",tokenEntity.token)
                    realContainer.updateRequestState {
                        copy(false,true,false)
                    }
                    realContainer.updateUiState {
                        SplashState(true, tokenEntity,false,"")
                    }
                }
        }

    }

    //构建启屏定时器
    fun startTimmer(){
        viewModelScope.launch (Dispatchers.IO){
            var index = 5
            while(index>0){
                delay(1000)
                launch (Dispatchers.Main){
                    realContainer.updateUiState {
                        SplashState(false,TokenEntity(""),true,""+index)
                    }
                }
                index--
                if (index ==0){
                        ARouter.getInstance()
                            .build("/app/mainactivity").navigation()
                }
            }
        }
    }


}